package response

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"websocket/model"
)

type Response struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

//刷新用户列表
type UserListMessage struct {
	MType       int            `json:"type"` //消息类型 1 系统消息  2 群聊消息  3 私聊消息  4 系统操作
	Message     string         `json:"msg"`  //消息内容
	UserInfo    model.UserInfo `json:"userInfo"`
	OnlineCount int            `json:"online_count"` //当前的用户列表
}

//接收消息解析
func Parse(data []byte) (model.MessageItem, error) {
	var messageItem model.MessageItem
	if err := json.Unmarshal(data, &messageItem); err != nil {
		return messageItem, err
	}
	return messageItem, nil
}

//输出json字符串
func ChatResult(data model.MessageItem, info model.UserInfo) []byte {
	//Message:= data
	t := time.Now().Unix()
	Message := &model.MessageItem{
		MType:    data.MType,
		Message:  data.Message,
		From:     data.From,
		To:       data.To,
		ToTime:   t,
		UserInfo: info,
	}
	b, err := json.Marshal(Message)
	if err != nil {
		return nil
	}
	return b
}

//输出json字符串
func Result2(data model.MessageItem, info model.UserInfo, onlineCount int) []byte {

	Message := &UserListMessage{
		MType:       data.MType,
		Message:     data.Message,
		UserInfo:    info,
		OnlineCount: onlineCount,
	}
	b, err := json.Marshal(Message)
	if err != nil {
		return nil
	}
	return b
}

func Result(code int, data interface{}, msg string, c *gin.Context) {
	// 开始时间
	c.JSON(http.StatusOK, Response{
		code,
		data,
		msg,
	})
}

func Ok(c *gin.Context) {
	Result(http.StatusOK, map[string]interface{}{}, "操作成功", c)
}

func OkWithMessage(message string, c *gin.Context) {
	Result(http.StatusOK, map[string]interface{}{}, message, c)
}

func OkWithData(data interface{}, c *gin.Context) {
	Result(http.StatusOK, data, "操作成功", c)
}

func OkWithDetailed(data interface{}, message string, c *gin.Context) {
	Result(http.StatusOK, data, message, c)
}

func Fail(c *gin.Context) {
	Result(http.StatusBadRequest, map[string]interface{}{}, "操作失败", c)
}

func FailWithMessage(message string, c *gin.Context) {
	Result(http.StatusBadRequest, map[string]interface{}{}, message, c)
}
func FailWithServerError(message string, c *gin.Context) {
	Result(http.StatusInternalServerError, map[string]interface{}{}, message, c)
}
func FailWithDetailed(data interface{}, message string, c *gin.Context) {
	Result(http.StatusBadRequest, data, message, c)
}
